class Solution {
    public boolean validateStackSequences(int[] pushed, int[] popped) {
        int pushedlen = pushed.length,poppedlen = popped.length;
        if(0 == pushedlen && 0 == poppedlen) {
            return true;
        }
        if(0 == pushedlen || 0 == poppedlen) {
            return false;
        }
        Stack<Integer> stack = new Stack<>();
        stack.add(pushed[0]);
        int i = 1 , j = 0;
        
        while(i<pushedlen || j<poppedlen) {
            while(stack.isEmpty() || stack.peek() != popped[j]) {
                if(i == pushedlen) {
                    return false;
                }
                stack.push(pushed[i++]);
            }
            while(!stack.isEmpty() && j < poppedlen && stack.peek() == popped[j]) {
                stack.pop();
                j++;
            }
        }
        return true;
    }
}